/*
 * Copyright 2017-2101 Innel.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hykj.xxltest.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hykj.xxltest.base.BaseService;
import com.hykj.xxltest.base.MsgException;
import com.hykj.xxltest.config.Config;
import com.hykj.xxltest.mapper.UserVerifyMapper;
import com.hykj.xxltest.model.UserVerifyModel;
import org.springframework.stereotype.Service;

/**
 * 验证码
 *
 * @author innel
 * @email 2638086622@qq.com
 * @date 2018-03-14 17:09:08
 */
@Service
public class UserVerifyService extends BaseService<UserVerifyModel, UserVerifyMapper> {

    /**
     * 验证码已使用
     * @param id
     */
    public void clearnVerify(Integer id){

        if(id==null){
            return;
        }
        UserVerifyModel userVerifyModel = new UserVerifyModel();
        userVerifyModel.setStatus(-1);
        userVerifyModel.setId(id);
        mapper.update(userVerifyModel);
    }



    /** 发送短信方法
     public boolean sendSDK2(String phone, String code) {
     TaobaoClient client = new DefaultTaobaoClient(Config.accessUrl, Config.accessKeyId, Config.accessKeySecret);
     AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
     req.setExtend("1");
     //必须填写normal
     req.setSmsType("normal");
     //你应用的名字
     req.setSmsFreeSignName("智享婴品");
     //电话号码
     req.setRecNum(phone);
     //模板
     req.setSmsTemplateCode("SMS_115180061");
     //模板中的参数，按照实际情况去
     req.setSmsParamString("{name:'" + code + "'}");

     try {
     AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
     // 这里是我设置的一个保存验证码 机制。按照实际需求，自行设计
     logger.info(rsp.getBody());
     if (rsp.getResult().getSuccess())
     return true;
     else
     throw  new MsgException(-1, "发送短信失败");
     } catch (ApiException e) {
     e.printStackTrace();
     }
     throw  new MsgException(-1, "发送短信失败");
     }

     */


    public void sendSDK(String phone,String code,String type,String name,String content) {
        try {

            String productNew = "全保网";


            //设置超时时间-可自行调整
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化ascClient需要的几个参数
            final String product = "Dysmsapi";//短信API产品名称
            final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名
//替换成你的AK
            final String accessKeySecret = Config.accessKeySecret;//你的accessKeySecret，参考本文档步骤2
//初始化ascClient,暂时不支持多region
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",Config. accessKeyId,
                    accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
            request.setPhoneNumbers(phone);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName("全保网");
            if (type == "0"){
                //必填:短信模板-可在短信控制台中找到
                request.setTemplateCode("SMS_7305289");
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.setTemplateParam("{\"code\":\""+code+"\",\"product\":\""+ productNew +"\"}");
            }
            if (type == "1"){
                //必填:短信模板-可在短信控制台中找到
                request.setTemplateCode("SMS_139236256");
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//                request.setTemplateParam("{\"code\":\""+code+"\",\"product\":\""+ productNew +"\"}");
            }
            if (type == "2"){
                //必填:短信模板-可在短信控制台中找到
                request.setTemplateCode("SMS_139226371");
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.setTemplateParam("{\"code\":\""+code+"\",\"name\":\""+ name +"\",\"content\":\""+content+"\"}");
            }

            //可选-上行短信扩展码(无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            // request.setOutId("yourOutId");
//请求失败这里会抛ClientException异常
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
//请求成功
                return ;
            }
            logger.info(sendSmsResponse.getCode()+" "+sendSmsResponse.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw  new MsgException(-1, "发送短信失败");

        }
        throw  new MsgException(-1, "发送短信失败");

    }

    public void sendEmail(String email,String code) {

//        // 1.创建一个程序与邮件服务器会话对象 Session
//        Properties props = new Properties();
//        props.setProperty("mail.transport.protocol", "SMTP");
//        props.setProperty("mail.smtp.host", "smtp.163.com");
//        props.setProperty("mail.smtp.port", "25");
//        // 指定验证为true
//        props.setProperty("mail.smtp.auth", "true");
//        props.setProperty("mail.smtp.timeout","1000");
//        // 验证账号及密码，密码需要是第三方授权码
//        Authenticator auth = new Authenticator() {
//            public PasswordAuthentication getPasswordAuthentication({
//                return new PasswordAuthentication("*******@163.com", "*******");
//            }
//        };
//        Session session = Session.getInstance(props, auth);
//
//// 2.创建一个Message，它相当于是邮件内容
//        Message message = new MimeMessage(session);
//// 设置发送者
//        message.setFrom(new InternetAddress("*******@163.com"));
//// 设置发送方式与接收者
//        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
//// 设置主题
//        message.setSubject("邮件发送测试");
//// 设置内容
//        message.setContent(emailMsg, "text/html;charset=utf-8");
//
//// 3.创建 Transport用于将邮件发送
//        Transport.send(message);

    }

}